﻿using System;
using System.Diagnostics;
using System.Web;
using System.Web.UI;

namespace Morus.Presentation
{
    public abstract class PageView : Page, IView
    {
        private bool _throwExceptionIfNoPresenterBound;
        private bool _registeredWithPageViewHost;
        private HttpContextBase _httpContext;

        protected PageView()
        {
            AutoDataBind = true;
            ThrowExceptionIfNoPresenterBound = true;
        }

        protected virtual bool AutoDataBind { get; set; }

        public virtual bool ThrowExceptionIfNoPresenterBound
        {
            [DebuggerStepThrough]
            get
            {
                return _throwExceptionIfNoPresenterBound;
            }
            set
            {
                if (_registeredWithPageViewHost)
                {
                    throw new InvalidOperationException("ThrowExceptionIfNoPresenterBound can only be set prior to the control's Init event. The best place to set it is in the control's constructor.");
                }
                _throwExceptionIfNoPresenterBound = value;
            }
        }

        public HttpContextBase HttpContext
        {
            get
            {
                return _httpContext ?? (_httpContext = new HttpContextWrapper(Context));
            }
        }

        protected override void OnInit(EventArgs e)
        {
            _registeredWithPageViewHost = true;

            PageViewHost.Register(this, HttpContext, AutoDataBind);

            base.OnInit(e);
        }

        public virtual bool IsAjax
        {
            get
            {
                HttpRequestBase request = HttpContext.Request;
                return request != null && (request["X-Requested-With"] == "XMLHttpRequest" || (request.Headers != null && request.Headers["X-Requested-With"] == "XMLHttpRequest"));
            }
        }
    }
}